<template>
  <div>
    <!-- 面包屑视图 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20"
        ><el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getMengtr"
          >
            <el-button slot="append" icon="el-icon-search" @click="getMengtr">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加按钮</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userschanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showedialogVisible(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="icondelete(scope.row.id)"
            >
            </el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
              ><el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="getroleVisible(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="butanniu"
    >
      <el-form
        :model="addForm"
        :rules="ruladdForm"
        ref="refaddForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobild">
          <el-input v-model="addForm.mobild"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户名"
      :visible.sync="edialogVisible"
      width="50%"
      @close="qedialogVisible"
    >
      <el-form
        ref="eiaddFormref"
        :model="eiaddForm"
        :rules="rulesaddForm"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="eiaddForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="eiaddForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="eiaddForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="edialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dedialogVisible">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色的对话框 -->

    <el-dialog title="分配角色" :visible.sync="roleVisible" width="50%">
      <div>
        <p>当前的用户：{{ userrole.username }}</p>
        <p>当前的角色：{{ userrole.role_name }}</p>
      </div>
      <span
        >重新分配角色:
        <el-select v-model="selsectmodeID" placeholder="请选择">
          <el-option
            v-for="item in rolelist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="proleVclick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证手机的规则
    const checkmobild = (rule, value, cd) => {
      const regmobild = /^(0||86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regmobild.test(value)) {
        return cd()
      }
      cd(new Error('请输入正确的电话号码'))
    }
    return {
      // 获取查询用户信息的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 保存请求回来的用户列表数据
      userList: [],
      total: 0,
      // 添加按钮的显示与隐藏
      dialogVisible: false,
      // 修改用户显示与隐藏
      edialogVisible: false,
      // 分配角色的对话框
      roleVisible: false,
      // 获取所有角色的数据元素
      rolelist: [],
      // 被分配的角色列表
      userrole: {},
      // 已选中的值
      selsectmodeID: '',

      eiaddForm: {
        email: '',
        mobild: ''
      },
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobild: ''
      },
      // 这是验证表单规则
      ruladdForm: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobild: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkmobild,
            trigger: 'blur'
          }
        ]
      },
      rulesaddForm: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkmobild,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getMengtr()
  },
  methods: {
    async getMengtr() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })

      // 如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      // 如果返回状态正常，将请求的数据保存在data中

      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    handleSizeChange(newSize) {
      // 当pagesize发生改变时触发
      this.queryInfo.pagesize = newSize
      this.getMengtr()
    },
    handleCurrentChange(newPage) {
      // 当pagenum发生改变时触发
      this.queryInfo.pagenum = newPage
      this.getMengtr()
    },
    async userschanged(userinfo) {
      // console.log(userinfo)

      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      // console.log(res)

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$$message.error('更新用状态失败')
      }
      this.$message.success('更新列表成功')
    },
    // 监听添加用户
    butanniu() {
      this.$refs.refaddForm.resetFields()
    },
    // 点击用户添加新的用户
    submitForm() {
      this.$refs.refaddForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.dialogVisible = false
        // 重新渲染用户列表
        this.getMengtr()
      })
    },
    async showedialogVisible(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.Error('获取用户列表失败')
      }
      // console.log(res)
      this.eiaddForm = res.data
      this.edialogVisible = true
    },
    // 修改的对话框的重置
    qedialogVisible() {
      this.$refs.eiaddFormref.resetFields()
    },
    // 修改表单验证
    dedialogVisible() {
      this.$refs.eiaddFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.eiaddForm.id,
          {
            email: this.eiaddForm.email,
            mobile: this.eiaddForm.mobile
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 关闭对话框
        this.edialogVisible = false
        // 重新刷新渲染列表
        this.getMengtr()
        // 提示更新列表成功
        this.$message.success('更新列表成功')
      })
    },
    // 获取用户需要删除的id
    async icondelete(id) {
      const res = await this.$confirm(
        '此操作将永久删除该用户名, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err
      })
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除用户的的信息
      const { data: ress } = await this.$http.delete('users/' + id)
      // console.log(ress)
      if (ress.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // console.log(ress)
      this.$message.success('删除成功')
      this.getMengtr()
    },
    async getroleVisible(userrole) {
      this.userrole = userrole
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        this.$message.error('分配角色失败')
      }
      this.rolelist = res.data

      this.roleVisible = true
    },
    // 分配角色的确定按钮
    async proleVclick() {
      if (!this.selsectmodeID) {
        this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userrole.id}/role`,
        {
          rid: this.selsectmodeID
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
    }
  }
}
</script>

<style lang="less" scoped></style>
